<?php

namespace Gwit\PlateformBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

use Gwit\PlateformBundle\Entity\User;
use Gwit\PlateformBundle\Form\UserType;

/**
 * User controller.
 *
 */
class UserController extends Controller
{
    /**
     * Lists all User entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entities = $em->getRepository('GwitPlateformBundle:User')->findAll();

        return $this->render('GwitPlateformBundle:User:index.html.twig', array(
            'entities' => $entities
        ));
    }

    /**
     * Finds and displays a User entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('GwitPlateformBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('GwitPlateformBundle:User:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),

        ));
    }

    /**
     * Displays a form to create a new User entity.
     *
     */
    public function newAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        
        $entity = new User();
        $form   = $this->createForm(new UserType($entity), $entity);

        return $this->render('GwitPlateformBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

    /**
     * Creates a new User entity.
     *
     */
    public function createAction()
    {
        $entity  = new User();
        $manipulator = @\FOS\UserBundle\FOSUserBundle::
        $request = $this->getRequest();
        $form    = $this->createForm(new UserType(), $entity);
        $form->bindRequest($request);
        
        //TODO : Vérifier la validité des informations 
        if ($form->isValid()) {
            //création de la cles de validation de compte
            $manipulator->create($entity->getUsername(), $entity->getPassword(), $entity->getEmail());
            //fin test
                    /*
            $key = md5(microtime(TRUE) * 100000);
            $entity->setCle($key);
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($entity);
            $em->flush();
            $url = $this->generateUrl('user_confirminscrip', array('log' => $entity->getUsername() ,'cle' => $key));
            //Envoi du mail de confirmation
            $message = \Swift_Message::newInstance()
                ->setSubject('Hello Email')
                ->setFrom('nourdinm@yahoo.fr')
                ->setTo($entity->getEmail())
                ->setBody($this->renderView('GwitPlateformBundle:otherdoc:emailconfirm.txt.twig', array('log' => $entity->getUsername(), 'valurl' => $url)));
            $this->get('mailer')->send($message);
            */
            //TODO : rediriger vers une pages de confirmation
            return $this->redirect($this->generateUrl('user_show', array('id' => $entity->getId())));
            
        }

        return $this->render('GwitPlateformBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }

    /**
     * Displays a form to edit an existing User entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('GwitPlateformBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm = $this->createForm(new UserType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('GwitPlateformBundle:User:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing User entity.
     *
     */
    public function updateAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('GwitPlateformBundle:User')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm   = $this->createForm(new UserType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $request = $this->getRequest();

        $editForm->bindRequest($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('user_edit', array('id' => $id)));
        }

        return $this->render('GwitPlateformBundle:User:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a User entity.
     *
     */
    public function deleteAction($id)
    {
        $form = $this->createDeleteForm($id);
        $request = $this->getRequest();

        $form->bindRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $entity = $em->getRepository('GwitPlateformBundle:User')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find User entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('user'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
    
    public function account_confirmationAction($log, $cle){
        $em = $this->getDoctrine()->getEntityManager();

        $entity = $em->getRepository('GwitPlateformBundle:User')->find($log);
        
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }
        
        //key verification
        if($entity->getCle() == $cle){
            $entity->setActif(1);
            $em->persist($entity);
            $em->flush();
            return $this->render('GwitPlateformBundle:Default:confirmation.html.twig', array('state' => 'reussi'));
        }else{
            //Gérer le cas ou la clés ne fonctionne pas.
            return $this->render('GwitPlateformBundle:Default:confirmation.html.twig', array('state' => 'echouer'));
        }
    }
    
    /**
     * Génération d'un vue list des utilisateurs avec formulaire lightbox
     * @return type 
     */
    public function testAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        
        $entity = new User();
        $form   = $this->createForm(new UserType(), $entity);

        return $this->render('GwitPlateformBundle:User:page_compte.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()
        ));
    }
    
    /**
     * Test du validator de donnée 
     * etat :  terminé à implémenter dans la validation du formulaire
     */
    public function testvalidatorAction(){
        $user = new User();
        
        //$user->setFirstName('toto');
        $user->setFamilyName('tata');
        //Login existant
        $user->setLogin('toto');
        $user->setPassword('c01nnnnnn');
        $user->setDateOfBirth(new \Datetime());
        //Email non existant
        $user->setEmail('coincon@gmail.com');
        $user->setSecurityAnswer('toto');
        $user->setSecurityQuestion('set');
        
        $validator = $this->get('validator');
        $liste_erreurs = $validator->validate($user);
        
        if(count($liste_erreurs) > 0)
        {
            return new Response(print_r($liste_erreurs, true));
        }
        else
        {
            return new Response("L'article est valide !");
        }
    }
}
